import React, { Component } from 'react';
import { observer } from 'mobx-react';

@observer
class Index extends Component {
    constructor () {
        super(...arguments);
        this.state = {};
        this.addOption = this.addOption.bind(this);
    }

    async getList () {
        const { appState } = this.props;
        await appState.initList();
    }

    componentDidMount () {
        this.getList();
    }

    addOption () {
        const { appState } = this.props;
        const obj = {
            name: appState.iptVal,
            age: appState.total,
            type: appState.total
        };
        appState.increment(obj);
    }

    changeIpt (val) {
        const { appState } = this.props;
        if (!val) {return;}
        appState.changeVal(val);
    }

    decrementOptions (idx) {
        const { appState } = this.props;
        appState.decrement(idx);
    }

    render () {
        const { appState } = this.props;
        return (
            <div>
                <input type="text" onKeyUp={(e) => {
                    const val = e.target.value;
                    this.changeIpt(val);
                    if (e.keyCode === 13) {
                        this.addOption();
                    }
                }} onChange={(e) => {
                    const val = e.target.value;
                    this.changeIpt(val);
                }} /> <button onClick={this.addOption}>添加</button>
                <ul>
                    {
                        appState.list.map((item, idx) => (
                            <li key={idx}>
                                {item.name} -- {item.age}
                                <button onClick={() => this.decrementOptions(idx)} style={{ marginLeft: '20px' }}>删除</button>
                            </li>
                        ))
                    }
                </ul>
                一共 {appState.total} 条数据
            </div>
        );
    }
}
export default Index;
